<template>
  <div class="apply-dialog">
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <LimitTech ref="LimitTech" @showTech="openTech" />
      <Tech ref="Tech" @showLimit="openHelp" />
      <div slot="title" class="flex flex-row align-center justify-content-end">
        <div class="btn-list flex flex-row align-center">
          <!-- <el-button type="primary" size="mini" @click="handlePrint(printData)">
            导出PDF
          </el-button> -->
          <el-button v-if="!pdfLoading" type="primary" size="mini" @click="outPutPdfFn()">
            导出PDF
          </el-button>
          <el-button v-else type="primary" size="mini" :loading="true">
            正在导出
          </el-button>
          <div class="pl15 pr15">
            上报人：<span class="primary-color">{{
              processStructureValue.workOrder.createdName
            }}</span>
          </div>
          <div class="pl15 pr15">
            最新状态：<span
              v-if="processStructureValue.workOrder.status == 2"
              class="danger-color"
            >已撤回</span>
            <span
              v-if="processStructureValue.workOrder.status == 3"
              class="danger-color"
            >已驳回</span>
            <span
              v-if="processStructureValue.workOrder.status == 0"
              class="primary-color"
            >{{ processStructureValue.workOrder.current_state_name }}</span><span
              v-if="processStructureValue.workOrder.principals != ''"
              class="ml20"
            >当前处理人：</span><span
              v-if="processStructureValue.workOrder.principals != ''"
              class="danger-color"
            >【{{ processStructureValue.workOrder.principals }}】</span>
          </div>
          <div class="ml20" @click="handleClose">
            <i class="el-icon-close cursor-p font22 line-height-32" />
          </div>
        </div>
      </div>
      <div id="pdfHtml" class="app-container flex flex-row">
        <div class="left flex-auto">
          <el-form ref="ruleForm" label-width="120px" class="" />
          <div v-if="dialogVisible" class="text item reviewFrom">
            <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
              <el-card
                v-show="
                  currentNode.hideTpls === undefined ||
                    currentNode.hideTpls === null ||
                    currentNode.hideTpls.indexOf(tplItem.form_structure.id) ===
                    -1
                "
                :key="tplIndex"
                class="box-card apply-box mb20"
              >
                <div
                  slot="header"
                  class="clearfix flex flex-row align-center height32"
                >
                  <div class="line" />
                  <span class="font16 ml10 flex-auto">{{
                    tplItem.form_name
                  }}</span>
                  <el-button
                    v-if="tplIndex == 0"
                    id="no-print"
                    type="danger"
                    round
                    icon="el-icon-thumb"
                    size="small"
                    @click="openHelp"
                  >申报指引</el-button>
                </div>
                <fm-generate-form
                  :ref="'generateForm-' + tplItem.id"
                  :preview="
                    !!(
                      (currentNode.hideTpls !== undefined &&
                      currentNode.hideTpls !== null &&
                      currentNode.hideTpls.indexOf(
                        tplItem.form_structure.id
                      ) !== -1) ||
                      (currentNode.writeTpls === undefined ||
                      currentNode.writeTpls === null ||
                      currentNode.writeTpls.indexOf(
                        tplItem.form_structure.id
                      ) === -1) ||
                      (isActiveProcessing && currentNode.activeOrder)
                    )
                  "
                  :remote="remoteFunc"
                  :value="tplItem.form_data"
                  :data="tplItem.form_structure"
                >
                  <el-form-item
                    slot="project_no_block"
                    label="项目编号"
                    prop="projectNo"
                    label-width="130px"
                    class="is-required"
                  >
                    <el-input
                      ref="input"
                      v-model="ruleForm.projectNo"
                      type="string"
                      disabled
                      placeholder="管理员填入"
                      style="{ width: 100% }"
                    />
                  </el-form-item>
                </fm-generate-form>
              </el-card>
            </template>
            <el-card class="box-card apply-box mb20">
              <div slot="header" class="clearfix flex flex-row align-center height32">
                <div class="line" />
                <span class="font16 ml10 flex-auto">审批历史</span>
              </div>
              <div class="text item pt10 pb10 pl10 pr10">
                <el-table :data="circulationHistoryList" border style="width: 100%" stripe max-height="600">
                  <el-table-column prop="id" label="#" align="center" type="index" width="70" />
                  <el-table-column prop="state" label="任务名称" align="center" />
                  <el-table-column prop="processor" label="处理人" align="center" />
                  <el-table-column prop="status" label="审批操作" align="center">
                    <template slot-scope="scope">
                      <div v-if="scope.row.status == 1">
                        审批通过
                      </div>
                      <div v-if="scope.row.status == 2">
                        提交成功
                      </div>
                      <div v-if="scope.row.status == 0">
                        审批驳回
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="remarks" label="审批意见" align="center" :show-overflow-tooltip="true" />
                  <el-table-column prop="cost_duration" label="耗时" align="center">
                    <template slot-scope="scope">
                      <div>{{ getDuration(scope.row.cost_duration) }}</div>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column prop="circulation" label="流转" align="center" /> -->
                  <el-table-column prop="create_time" label="处理时间" align="center" width="180" />
                  <el-table-column prop="status" label="状态" align="center" width="90">
                    <template slot-scope="scope">
                      <div v-if="scope.row.status == 3" class="warning-color">
                        待处理
                      </div>
                      <div v-else class="primary-color">
                        已处理
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </div>
        </div>
        <!-- <div class="right width350 ml10">
          <el-card class="box-card history-box mb20">
            <div
              slot="header"
              class="clearfix flex flex-row align-center height32"
            >
              <div class="line"></div>
              <span class="font16 ml10 flex-auto">审批历史</span>
            </div>
            <vue-scroll :ops="ops">
              <div class="timeline">
                <el-timeline v-if="timelineShow">
                  <el-timeline-item
                    v-for="item in timeLine"
                    :key="item.id"
                    :hide-timestamp="true"
                    icon="el-icon-my-time"
                    color="#277fd6"
                    size="large"
                  >
                    <div class="flex flex-column">
                      <div class="time">
                        <span class="text">{{ item.create_time }}</span>
                        <el-tag
                          :type="getHistoryTag(item)"
                          effect="dark"
                          size="small"
                          class="stateTag ml10"
                        >
                          {{ getHistoryState(item) }}
                        </el-tag>
                      </div>
                      <div
                        class="info"
                        v-if="item.status == 2 && item.target != ''"
                      >
                        <span class="label">上报人：</span
                        ><span class="detail">{{ item.processor }}</span>
                      </div>
                      <div class="info" v-else>
                        <span class="label">审批人：</span
                        ><span class="detail">{{ item.processor }}</span>
                      </div>
                      <div class="info">
                        <span class="label">审批节点：</span
                        ><span class="detail">{{ item.state }}</span>
                      </div>
                      <div
                        class="info flex flex-row"
                        v-if="item.status == 2 && item.target != ''"
                      ></div>
                      <div class="info flex flex-row" v-else>
                        <span class="label">审批意见：</span
                        ><span class="detail flex-auto">{{
                          item.remarks
                        }}</span>
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
                <div v-else class="empty-time mt100">
                  <img src="@/assets/empty.png" alt="" />
                  <span>暂时没有审批内容</span>
                </div>
              </div>
            </vue-scroll>
          </el-card>
        </div> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { Message, Loading } from 'element-ui'
import { GenerateForm } from '@/components/VueFormMaking'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)
import LimitTech from './limitTech/index.vue'
import Tech from './tech/index.vue'
import { getDuration } from '@/utils/costum'
import {
  processStructure,
  handleWorkOrder,
  activeOrder
} from '@/api/xjs/work-order'
import { listAllUser } from '@/api/system/sysuser'
import { getOrdinaryDeptList } from '@/api/system/dept'
import { mapGetters } from 'vuex'
import printJS from 'print-js'
export default {
  name: 'ApplyDialog',
  components: {
    LimitTech,
    Tech
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      timelineShow: false,
      timeLine: [],
      getDuration,
      pdfLoading: false,
      loadingFull: null,
      ops: {
        vuescroll: {
          mode: 'native',
          sizeStrategy: 'percent',
          detectResize: true,
          locking: true
        },
        scrollPanel: {
          maxHeight: 800
        },
        bar: {
          background: '#277fd6',
          size: '3px',
          keepShow: true
        },
        rail: {
          background: '#E0E8F0',
          opacity: 1,
          size: '3px',
          specifyBorderRadius: false,
          gutterOfEnds: '50px',
          gutterOfSide: '0px',
          keepShow: false
        }
      },
      printData: {
        printable: 'printFrom',
        header: '',
        ignore: ['no-print']
      },
      limitTechList: [],
      selectLimitData: [],
      loading: false,
      dialogVisible: false,
      limitTechVisible: false,
      isLoadingStatus: true,
      currentNode: {
        hideTpls: null,
        writeTpls: null
      },
      isActiveProcessing: false,
      tpls: [],
      remarks: '', // 备注信息
      alertMessage: '',
      nodeStepList: [],
      circulationHistoryList: [],
      activeIndex: 0,
      processStructureValue: {
        workOrder: { title: '' }
      },
      ruleForm: {
        title: '',
        projectNo: '',
        process: '',
        classify: '',
        state_id: '',
        state: '',
        source_state: '',
        processor: '',
        process_method: '',
        tpls: [],
        tasks: []
      },
      processId: null,
      workOrderId: null,
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        }
      }
    }
  },
  computed: {
    ...mapGetters(['name', 'userId'])
  },
  methods: {
    getHistoryState(item) {
      if (item.circulation == '结束') {
        return '审批完成'
      } else if (item.circulation == '已撤回') {
        return '已撤回'
      } else {
        if (item.status == 2) {
          if (item.target != '') {
            return '提交申报'
          } else {
            return '转交'
          }
        } else if (item.status == 0) {
          return '审批驳回'
        } else {
          return '审批通过'
        }
      }
    },
    getHistoryTag(item) {
      if (item.circulation == '结束') {
        return 'success'
      } else if (item.circulation == '已撤回') {
        return 'danger'
      } else {
        if (item.status == 2) {
          if (item.target != '') {
            return ''
          } else {
            return 'warning'
          }
        } else if (item.status == 0) {
          return 'danger'
        } else {
          return 'success'
        }
      }
    },
    downLoadDoc(type) {
      var a = document.createElement('a')
      switch (type) {
        case 1:
          a.href =
            '/static/xjs/非限制类使用——甘肃省人民医院医疗技术临床应用审核申请书（操作技术）.docx'
          a.download =
            '非限制类使用——甘肃省人民医院医疗技术临床应用审核申请书（操作技术）.docx'
          break
        case 2:
          a.href =
            '/static/xjs/非限制类使用——甘肃省人民医院医疗技术临床应用审核申请书（检验检查）.docx'
          a.download =
            '非限制类使用——甘肃省人民医院医疗技术临床应用审核申请书（检验检查）.docx'
          break
        case 3:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 4:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 5:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
      }
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    openHelp() {
      this.$refs.Tech.close()
      this.$refs.LimitTech.open()
    },
    openTech() {
      this.$refs.LimitTech.close()
      this.$refs.Tech.open()
    },
    outPutPdfFn() {
      const vm = this
      const A4_WIDTH = 592.28
      const A4_HEIGHT = 841.89 // $myLoading 自定义等待动画组件，实现导出事件的异步等待交互
      this.pdfLoading = true
      this.loadingFull = Loading.service({
        target: document.querySelector('.app-wrapper'),
        lock: true,
        text: '正在导出中，请稍后……',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'zIndex9999'
      })
      vm.$nextTick(() => {
        // dom的id。
        const target = document.getElementById('pdfHtml')
        const pageHeight = target.scrollWidth / A4_WIDTH * A4_HEIGHT
        // 获取分割dom，此处为class类名为item的dom
        const lableListID = document.getElementsByClassName('item-excel')
        // 进行分割操作，当dom内容已超出a4的高度，则将该dom前插入一个空dom，把他挤下去，分割
        for (let i = 0; i < lableListID.length; i++) {
          const multiple = Math.ceil((lableListID[i].offsetTop + lableListID[i].offsetHeight / 2) / pageHeight)
          if (this.isSplit(lableListID, i, multiple * pageHeight)) {
            const divParent = lableListID[i].parentNode
            // 获取该div的父节点
            const newNode = document.createElement('div')
            newNode.className = 'emptyDiv'
            newNode.style.background = '#ffffff'
            const _H = multiple * pageHeight - (lableListID[i].offsetTop + lableListID[i].offsetHeight)
            newNode.style.height = _H + 30 + 'px'
            newNode.style.width = '100%'
            const next = lableListID[i].nextSibling
            // 获取div的下一个兄弟节点
            // // 判断兄弟节点是否存在
            if (next) {
              // 存在则将新节点插入到div的下一个兄弟节点之前，即div之后
              divParent.insertBefore(newNode, next)
            } else {
              // 不存在则直接添加到最后,appendChild默认添加到divParent的最后
              divParent.appendChild(newNode)
            }
          }
        }
        // 传入title和dom标签，此处是 #content// 异步函数，导出成功后处理交互
        this.getPdf(`${this.processStructureValue.workOrder.title}`, '#pdfHtml').then(() => {}).catch(() => {})
        setTimeout(() => {
          this.loadingFull.close()
          this.pdfLoading = false
        }, 2000)
        this.pdfLoading = false
      })
    },
    isSplit(nodes, index, pageHeight) {
      // 计算当前这块dom是否跨越了a4大小，以此分割
      if (nodes[index].offsetTop + nodes[index].offsetHeight < pageHeight && nodes[index + 1] &&
        nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight > pageHeight) { return true }
      return false
    },
    handlePrint(params) {
      printJS({
        maxWidth: 1920,
        documentTitle: '甘肃省人民医院医务一网通办',
        printable: params.printable, // 'printFrom',
        type: params.type || 'html',
        header: params.header, // '表单',
        targetStyles: ['*'],
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null
      })
    },
    handleClose(val) {
      this.dialogVisible = false
    },
    open(processId, workOrderId) {
      this.processId = processId
      this.workOrderId = workOrderId

      this.getProcessNodeList()
    },

    getProcessNodeList() {
      processStructure({
        processId: this.processId,
        workOrderId: this.workOrderId
      }).then(response => {
        this.isActiveProcessing = false
        this.processStructureValue = response.data
        this.circulationHistoryList = this.processStructureValue.circulationHistory
        if (this.circulationHistoryList.length > 0) {
          this.timelineShow = true
          this.timeLine = this.circulationHistoryList
        }
        this.ruleForm.projectNo = this.processStructureValue.workOrder.projectNo
        // 获取当前展示节点列表
        this.nodeStepList = []
        if (this.processStructureValue.nodes) {
          for (var i = 0; i < this.processStructureValue.nodes.length; i++) {
            if (
              this.processStructureValue.nodes[i].id ===
              this.processStructureValue.workOrder.current_state
            ) {
              // 当前节点
              this.nodeStepList.push(this.processStructureValue.nodes[i])
              this.activeIndex = this.nodeStepList.length - 1
              if (i + 1 === this.processStructureValue.nodes.length) {
                this.activeIndex = this.nodeStepList.length
              }
              this.currentNode = this.processStructureValue.nodes[i]
            } else if (!this.processStructureValue.nodes[i].isHideNode) {
              // 非隐藏节点
              this.nodeStepList.push(this.processStructureValue.nodes[i])
            }
          }
        }

        // 如果回退到初始节点则可编辑。
        if (this.activeIndex === 0 && this.currentNode.clazz === 'start') {
          this.currentNode.writeTpls = []
          for (var tplTmp of this.processStructureValue.tpls) {
            this.currentNode.writeTpls.push(tplTmp.form_structure.id)
          }
        }

        // 判断是否需要主动处理
        for (var stateValue of this.processStructureValue.workOrder.state) {
          if (
            this.processStructureValue.workOrder.current_state ===
              stateValue.id &&
            stateValue.processor.length > 1
          ) {
            this.isActiveProcessing = true
            break
          }
        }
        this.dialogVisible = true
        this.isLoadingStatus = false
      })
    },
    submitAction(item) {
      var promiseList = []
      this.tpls = []
      for (var tpl of this.processStructureValue.tpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id
        })
        promiseList.push(this.$refs['generateForm-' + tpl.id][0].getData())
      }
      Promise.all(promiseList).then(values => {
        for (var tplDataIndex in this.tpls) {
          this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
        }
        handleWorkOrder({
          tasks: this.processStructureValue.process.task,
          source_state: this.processStructureValue.workOrder.current_state,
          target_state: item.target,
          circulation: item.label,
          flow_properties:
            item.flowProperties === undefined
              ? 2
              : parseInt(item.flowProperties),
          work_order_id: parseInt(this.workOrderId),
          remarks: this.remarks,
          is_exec_task: item.isExecuteTask,
          tpls: this.tpls
        }).then(response => {
          if (response.code === 200) {
            this.dialogVisible = false
            this.$emit('refreshTable')
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/* 去掉全选按钮 */
::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
  display: none !important;
}

::v-deep .el-table .disabledCheck .cell::before {
  content: "请选择";
  text-align: center;
  line-height: 37px;
}
.app-container {
  max-width: 1530px;
  margin: 0 auto;
  // background: #ebf4fa;
  border-radius: 12px;
  .apply-box {
    border-radius: 15px;
    .line {
      height: 22px;
      width: 5px;
      background: #277fd6;
    }
  }
  .history-box {
    border-radius: 15px;
    .line {
      height: 22px;
      width: 5px;
      background: #277fd6;
    }
  }
}
</style>
